<template>
  <!-- <template v-if="isLogin"></template> -->
  <template v-if="isLogin">
    <div class="tabbar">
      <vab-icon icon="arrow-left-s-line" style="" class="back-icon" @click="backToSelect"
        v-if="!studyInfoUnavailable" />
      <h1 class="nav-title">学习</h1>
    </div>
    <div class="container" v-if="studyInfoUnavailable">
      <div class="resource-list">
        <div class="resource-container" @click="() => navigateToStudy(item)" v-for="item of resourceList">
          <el-row class="resource-title">
            <el-col :span="24">{{ item.name }}</el-col>
          </el-row>
          <el-row justify="end">
            <el-tag>{{ item.drillName }}</el-tag>
          </el-row>
          <!-- <el-row class="resource-desc">
            <el-col :span="24">{{ item.desc }}</el-col>
          </el-row> -->
          <!-- <el-divider /> -->
        </div>
      </div>
    </div>
    <div class="study" v-else>
      <el-row justify="center" style="margin-top: 20px">
        <el-button @click="studyBegin">开始学习</el-button>
        <el-button @click="studyEnd" :disabled="studyEndDisabled">{{ studyEndText }}</el-button>
      </el-row>
      <el-row>
        <video v-if="studyInfo.type === 'video'" class="video" ref="video" id="video" controls>
          <source :src="studyInfo.url" type="video/mp4" />
        </video>
        <div v-else-if="studyInfo.type === 'document' && studyInfo.url.split('.').reverse()[0] === 'pdf'"
          style="width: 100vw; height: 100%">
          <div style="
              margin-top: 20px;
              height: calc(100% - 250px);
              overflow: scroll;
            ">
            <vue-office-pdf style="width: 100%; height: 100vh" :src="studyInfo.url" />
          </div>
        </div>
        <div v-else-if="studyInfo.type === 'document' && studyInfo.url.split('.').reverse()[0] === 'docx'"
          style="width: 100vw; height: 100%">
          <div style="
              margin-top: 20px;
              height: calc(100% - 250px);
              overflow: scroll;
            ">
            <vue-office-docx style="width: 100%; height: 100vh" :src="studyInfo.url" />
          </div>
        </div>
        <div
          v-else-if="studyInfo.type === 'document' && ['xls', 'xlsx'].includes(studyInfo.url.split('.').reverse()[0])"
          style="width: 100vw; height: 100%">
          <div style="
              margin-top: 20px;
              height: calc(100% - 250px);
              overflow: scroll;
            ">
            <vue-office-excel style="width: 100%; height: 100vh" :src="studyInfo.url" />
          </div>
        </div>
        <div v-else-if="studyInfo.type === 'document' && studyInfo.url.split('.').reverse()[0] === 'pptx'"
          style="width: 100vw; height: 100%">
          <div style="
              margin-top: 20px;
              height: calc(100% - 250px);
              overflow: scroll;
            ">
            <vue-office-ppt style="width: 100%; height: 100vh" :src="studyInfo.url" />
          </div>
        </div>
      </el-row>
      <!-- <el-row justify="center" v-if="studyInfo.type === 'video'">
        <el-button @click="studyBegin">开始学习</el-button>
        <el-button @click="studyEnd">结束学习</el-button>
      </el-row> -->
    </div>
  </template>
  <div v-else style="
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    ">
    <h1 style="text-align: center">登录</h1>
    <el-form :model="loginForm" ref="formRef" :rules="rules" label-position="top" style="width: 80%">
      <el-row>
        <el-form-item prop="staffName" label="姓名" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['staffName']" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item prop="staffIdentity" label="身份证号" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['staffIdentity']" />
        </el-form-item>
      </el-row>
      <!-- <el-row>
        <el-form-item prop="phone" label="电话号码" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['phone']" />
        </el-form-item>
      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="companyName" label="电话号码" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['companyName']" />
        </el-form-item>
      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="areaId" label="省市区" label-width="80px" style="width: 100%">
          <CitySelect v-model="loginForm['areaId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" />
        </el-form-item>

      </el-row> -->
      <!-- <el-row>
        <el-form-item prop="provinceId" label="省" label-width="80px" style="width: 100%"> -->
          <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
            <!-- <SingleLayerSelect v-model="loginForm['provinceId']" :options="provinceList" @update:modelValue="(v)=>getCityList(v)"/>
        </el-form-item>

      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="cityId" label="市" label-width="80px" style="width: 100%"> -->
          <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
            <!-- <SingleLayerSelect v-model="loginForm['cityId']" :options="cityList" @update:modelValue="(v)=>getAreaList(v)"/>
        </el-form-item>
      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="areaId" label="区" label-width="80px" style="width: 100%"> -->
          <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
            <!-- <SingleLayerSelect v-model="loginForm['areaId']" :options="areaList" @update:modelValue="(v)=>getTownList(v)"/>
        </el-form-item>
      </el-row> -->

    <!-- <el-row>
      <el-form-item prop="townId" label="乡镇" label-width="80px" style="width: 100%">
        <SingleLayerSelect :options="townList" v-model="loginForm['townId']" />
      </el-form-item>
    </el-row>
 -->
      <el-row justify="center">
        <el-button type="primary" style="width: 100%" @click="login">确认</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import VueOfficeDocx from "@vue-office/docx";
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeExcel from "@vue-office/excel";
import VueOfficePpt from "@vue-office/pptx";
import "@vue-office/docx/lib/index.css";
import { FormRules } from "element-plus";
import AccountApi from "~/src/api/AccountApi";
import { useUserStore } from "~/src/store/modules/user";
import VDialog from "~/src/utils/dialogUtil";

const formRef = useTemplateRef("formRef");
const loginForm = reactive<Record<string, any>>({});
const videoRef = useTemplateRef<HTMLVideoElement>("video");
const currentMaterialId = ref();
const isLogin = ref(false);
const studyEndDisabled = ref(false)
const studyEndText = ref("20秒后可结束学习")
let endDate: Date
let endTimer: any
const rules = ref<FormRules>({
  staffName: {
    required: true,
    message: "请输入姓名",
    trigger: "blur",
  },
  staffIdentity: {
    required: true,
    message: "请输入身份证号码",
    trigger: "blur",
  },
  // phone: {
  //   required: true,
  //   message: "请输入手机号",
  //   trigger: "blur",
  // },
  // provinceId: {
  //   required: true,
  //   message: "请选择省",
  //   trigger: "blur",
  // },
  // cityId: {
  //   required: true,
  //   message: "请选择市",
  //   trigger: "blur",
  // },
  // areaId: {
  //   required: true,
  //   message: "请选择区域",
  //   trigger: "blur",
  // },
  // townId: {
  //   required: true,
  //   message: "请输入乡镇",
  //   trigger: "blur",
  // },
});

const studyInfo = ref({
  // type: "docx",
  // url: "https://jw-pub-test.oss-cn-beijing.aliyuncs.com/a422e56d7fab43d5b7ab1a9574839f1d.docx",
});
const companyId = ref("");
const drillInfoId = ref("");
const materialId = ref("");
const store = useUserStore();
const router = useRouter();
const resourceList = ref([]);
const studyInfoUnavailable = computed(
  () => studyInfo.value === undefined || Object.keys(studyInfo.value).length === 0
);

const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const townList = ref([])

function getProvinceList() {
  AccountApi.getProvinceList({}).then((res) => {
    provinceList.value = res.data
      .map((item: any) => ({ label: item.province, value: item.provinceId }))
  })
}

function getCityList(v: any) {
  AccountApi.getCityList({ provinceId: v }).then((res) => {
    cityList.value = res.data
      .map((item: any) => ({ label: item.city, value: item.cityId }))
  })
}

function getAreaList(v: any) {
  AccountApi.getNormalAreaList({ cityId: v }).then((res) => {
    areaList.value = res.data
      .map((item: any) => ({ label: item.area, value: item.areaId }))
  })
}

function getTownList(v: any) {
  AccountApi.getTownList({ areaId: v }).then((res) => {
    console.log("乡镇", res.data.
      records
    );
    townList.value = res.data.records
      .map((item: any) => ({ label: item.town, value: item.townId }))
  })
}

function backToSelect() {
  studyInfo.value = {};
}
const num = ref(1);
const scale = 0.65;
let outputScale = window.devicePixelRatio || 1;
let transform =
  outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;

function navigateToStudy(studyItem: any) {
  studyInfo.value = studyItem;
  currentMaterialId.value = studyItem.id;
  endDate = new Date()
  endDate.setSeconds(endDate.getSeconds() + 20)
  endTimer = setInterval(() => {
    const currentDate = new Date()
    const mins = endDate.getMinutes() - currentDate.getMinutes()
    const seconds = endDate.getSeconds() - currentDate.getSeconds()
    if (mins === 0 && seconds === 0) {
      studyEndText.value = "结束学习"
      studyEndDisabled.value = false
      clearInterval(endTimer)
    } else {
      studyEndText.value = `${(mins * 60) + seconds}秒后可结束学习`
      studyEndDisabled.value = true
    }
  }, 1000)
}

// 开始学习
function studyBegin() {
  if (studyInfo.value.type === "video") {
    videoRef.value?.play();
  }
  AccountApi.studyBegin({
    drillId: drillInfoId.value,
    materialId: currentMaterialId.value,
  }).then(({ message }) => {
    $baseMessage(message, "success", "vab-hey-message-success");
  });
}

// 结束学习
function studyEnd() {
  if (studyInfo.value.type === "video") {
    videoRef.value?.pause();
  }
  AccountApi.studyEnd({ drillId: drillInfoId.value, materialId: currentMaterialId.value }).then(({ message }) => {
    $baseMessage(message, "success", "vab-hey-message-success");
  });
}

onMounted(async () => {
  const url = new URL(window.location.href);
  console.log("url", url);
  companyId.value = url.searchParams.get("companyId") ?? "";
  drillInfoId.value = url.searchParams.get("drillInfoId") ?? "";
  console.log("store gettoken", store.getToken);
  getProvinceList()
  if (store.getToken !== "") {
    materialId.value = url.searchParams.get("materialId") ?? "";
  } else {
    login();
  }
});

function action(obj?: {id?:any, name?:string, type?: any}) {
  // const form:Record<any,any> = {}
  // obj.id && (form.companyId = obj.id)
  // form.companyName = obj.name
  // obj.type && (form.companyType = obj.type)
  
  AccountApi.h5UserLogin({
    ...loginForm,
    drillId: drillInfoId.value
  }).then(({ data, message }) => {
    console.log("data token", data.token);
    store.setToken(data.token);
    AccountApi.getDrillInfoDetail({
      drillInfoId: drillInfoId.value,
    }).then((infoData) => {
      console.log("drill info detail", infoData);
      resourceList.value =
        infoData.data.drillInfoMaterialList.map((x) => ({
          id: x.id,
          name: x.materialName,
          drillName: x.drillName,
          type: x.materialType,
          url: x.materialUrl,
        }));

      // 没有培训材料的情况
      if (!infoData.data.drillInfoMaterialList || infoData.data.drillInfoMaterialList.length === 0) {
        $baseAlert("相关活动暂未设置学习资料", "温馨提示")
      } else {
        isLogin.value = true;
      }
    });
  });
}

// const companyList = ref<{label: any, value: any, type: any}[]>([])
function login() {
  formRef.value?.validate((validate) => {
    if (validate) {
      console.log("validate");
      action({})

      // const companyListItem = {
      //   staffName: loginForm.staffName,
      //   staffIdentity: loginForm.staffIdentity,
      //   phone: loginForm.phone
      // }
      // AccountApi.getCompanyList(companyListItem).then(res => {
      //   console.log("res11111", res.data);


      //   if (res) {
      //     companyList.value = res.data.map(x => ({ label: x.companyName, value: x.companyId, type: x.companyInfo.type }))
      //     console.log(11111, companyId.value);

      //     // 管理端
      //     if (companyId.value && companyId.value === "0") {

      //       if (companyList.value.length > 0) {
      //         if (companyList.value.length === 1) {
      //           const { value: id, label: name, type }  = companyList.value[0]
      //           action({id, name})
      //         } else {
      //           VDialog.open({
      //             title: "公司选择",
      //             content: {
      //               top: "35vh",
      //               //内容初始形式
      //               type: "component", //text:"",预留文本
      //               name: "/signin/companySelect",
      //               query: { options: companyList }
      //             },
      //             callBack: ({id, name}:{id: any,name: any, type: any}) => {
      //               action({id, name})
      //             },
      //             onClose: () => {
      //               console.log("对话框已关闭");
      //             },
      //           });
      //         }

      //       } else {
      //         // $baseMessage("用户不存在", "error")
      //         VDialog.open({
      //           title: "公司输入",
      //           content: {
      //             top: "35vh",
      //             //内容初始形式
      //             type: "component", //text:"",预留文本
      //             name: "/signin/company",
      //           },
      //           callBack: ({companyName: name, companyType: type}: {companyName: any, companyType: any}) => {
      //             action({name, type})
      //           },
      //           onClose: () => {
      //             console.log("对话框已关闭");
      //           },
      //         });
      //       }

      //     } else {
      //       // 商户端
      //       const currentCompany = companyList.value.find(x=>x.value === companyId.value)
      //       if (currentCompany) {
      //         action({id: companyId.value, name: currentCompany.label})
      //       } else {
      //         $baseMessage("用户不存在", "error")
      //       }
      //     }
      //   }
      // })
      // if (companyId.value && companyId.value === "0") {
      //   VDialog.open({
      //     title: "公司选择",
      //     content: {
      //       top: "35vh",
      //       //内容初始形式
      //       type: "component", //text:"",预留文本
      //       name: "/exam/companySelect",
      //       query: { staffName: loginForm.staffName, staffIdentity: loginForm.staffIdentity, phone: loginForm.phone }
      //     },
      //     callBack: (data: any) => {
      //       companyId.value = data
      //       action()
      //     },
      //     onClose: () => {
      //       console.log("对话框已关闭");
      //     },
      //   });
      // }

    }
  });
}
</script>

<style scoped>
.tabbar {
  display: flex;
  background-color: white;
  height: 60px;
  align-items: center;
}

.back-icon {
  font-size: 28px;
  margin-left: 20px;
}

.back-icon:active {
  color: var(--el-color-primary);
}

.nav-title {
  font-size: 18px;
  transform: translateX(-10px);
  margin: 0 auto;
}

.container {
  width: 100%;
  height: 100%;
  flex-direction: column;
  display: flex;
  justify-content: center;
  align-items: center;
}

.resource-list {
  width: 100%;
  height: 100%;
  overflow: scroll;
}

.resource-container {
  padding: 20px;
  border-radius: 10px;
  font-size: 18px;
  background-color: #fff;
  margin: 25px 20px;
}

.resource-title {
  line-height: 25px;
}

.resource-desc {
  font-size: 13px;
}

.file-box {
  width: 100%;
  height: calc(100% - 60px);
}

.study {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

#video {
  width: 100%;
  position: relative;
  margin: 30px auto 20px auto;
}
</style>
